﻿using nRoute.Components;
using nRoute.Navigation.Mapping;
using nRoute.Samples.Netflix.Data.Catalog;
using nRoute.Samples.Netflix.Views;
using nRoute.ViewModels;

namespace nRoute.Samples.Netflix.ViewModels
{
    [DefineNavigationContent("Content/Netflix/Title/", typeof(TitleView))]
    [MapViewModel(typeof(TitleView))]
    public class TitleViewModel 
        : NavigationViewModelBase
    {
        private const string MOVIE_TITLE_KEY = "MovieTitle";
        private const string TITLE_FORMAT = "{0}: {1}";

#region Properties

        public Title MovieTitle { get; private set; }

#endregion

#region Overrides

        protected override void OnIntialize(ParametersCollection state)
        {
            // if no data is passed in on initialization, it means it will be restored from state
            if (!state.ContainsKey(MOVIE_TITLE_KEY)) return;
            SetupMovieTitle((Title)state[MOVIE_TITLE_KEY]);
        }

        protected override void OnRestoreState(ParametersCollection state)
        {
            // if movie title is already loaded we don't load again
            if (MovieTitle != null) return;

            if (state.ContainsKey(MOVIE_TITLE_KEY))
            {
                SetupMovieTitle((Title)state[MOVIE_TITLE_KEY]);
            }
            else
            {
                // inform no loaded data
            }
        }

        protected override ParametersCollection OnSaveState()
        {
            if (MovieTitle != null)
            {
                return new ParametersCollection() 
                { 
                    new Parameter(MOVIE_TITLE_KEY, MovieTitle)
                };
            }
            else
            {
                return null;
            }
        }

#endregion

#region Helpers

        private void SetupMovieTitle(Title title)
        {
            base.Title = string.Format(TITLE_FORMAT, title.Type, title.Name);

            this.MovieTitle = title;
            NotifyPropertyChanged(() => MovieTitle);
                        
            if (title.Languages.Count == 0) title.Languages.LoadAsync();
            if (title.Cast.Count == 0) title.Cast.LoadAsync();
            if (title.Directors.Count == 0) title.Directors.LoadAsync();
            if (title.Genres.Count == 0) title.Genres.LoadAsync();
        }

#endregion

    }
}